<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\plugins\model;

use think\Db;
use think\Model;

/**
 * 模型
 */

load_trait('controller/Jump');
class DealerPlugin extends Model
{
    use \traits\controller\Jump;

    private $times = 0;
    private $param = [];
    private $users = [];
    private $users_id = 0;

    // 构造函数
    public function __construct($param = [], $users = [])
    {
        // 统一接收参数处理
        $this->times = getTime();
        $this->param = !empty($param) ? $param : [];
        $this->users = !empty($users) ? $users : [];
        $this->users_id = !empty($this->users['users_id']) ? intval($this->users['users_id']) : 0;
        parent::__construct();
    }

    // 初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 分销商数据信息表
        $this->dealer = Db::name('weapp_dealer');
        // 分销商申请表
        $this->dealerApply = Db::name('weapp_dealer_apply');
        // 分销商提现数据表
        $this->dealerWithdraw = Db::name('weapp_dealer_withdraw');
        // 分销商提现数据表
        $this->dealerMoneyLog = Db::name('weapp_dealer_money_log');
        // 分销设置
        $this->dealerConfig = getUsersConfigData('dealer');
        // 判断分销功能是否开启，未开启则返回会员中心
        if (!isset($this->dealerConfig['dealer_open']) || 0 === intval($this->dealerConfig['dealer_open'])) {
            if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
                $this->error('分销功能已关闭', url('user/Users/index'));
            } else {
                $this->success('分销功能已关闭', null, ['dealer_open'=>0, 'jumpPage'=>'/pages/user/user']);
            }
        }
        if (!in_array($this->param['action'], ['query', 'getApply', 'addApply', 'bindUsers'])) {
            // 如果分销商被冻结则提示并跳转到会员中心
            if (empty($this->users['dealer'])) {
                if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
                    $this->error('您还不是分销商', url('user/Users/index'));
                } else {
                    $this->success('您还不是分销商', null, ['dealer_id' => 0, 'jumpPage' => '/pages/user/user']);
                }
            } else if (isset($this->users['dealer']['dealer_status']) && 0 === intval($this->users['dealer']['dealer_status'])) {
                if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
                    $this->error('分销商已被冻结', url('user/Users/index'));
                } else {
                    $this->success('分销商已被冻结', null, ['dealer_status' => 0, 'jumpPage' => '/pages/user/user']);
                }
            }
        }
    }

    // 查询分销商申请数据
    public function queryDealerApply()
    {
        $where = [
            'users_id' => $this->users_id
        ];
        $dealerApply = $this->dealerApply->where($where)->find();
        if (empty($dealerApply) || (!empty($dealerApply) && in_array($dealerApply['review_status'], [1, 3]))) {
            $result = [
                'allowApply' => 1,
                'jumpPage' => '/pages/dealer/apply/apply',
            ];
            $this->unifyParamSuccess('允许申请', null, $result);
        }
    }

    // 获取分销商申请
    public function getDealerApply($isReturn = false)
    {
        // 分销商申请数据
        $result = [
            'action' => 'addApply',
            'mobile' => !empty($this->users['mobile']) ? $this->users['mobile'] : '',
            'nickname' => !empty($this->users['nickname']) ? $this->users['nickname'] : $this->users['username'],
            'dealer_mobile' => !empty($this->users['mobile']) ? $this->users['mobile'] : '',
            'dealer_name' => !empty($this->users['nickname']) ? $this->users['nickname'] : $this->users['username'],
        ];

        // 如果会员已绑定过上级分销商则获取绑定的分销商ID
        if (!empty($this->users['parent_users_id']) && !empty($this->users['parent_dealer_id'])) {
            $this->param['parent_users_id'] = intval($this->users['parent_users_id']);
        }

        // 如果存在推荐人则执行
        if (!empty($this->param['parent_users_id'])) {
            $dealerInfo = $this->getDealerInfo($this->param['parent_users_id']);
            $result['parent_users_id'] = !empty($dealerInfo['users_id']) ? intval($dealerInfo['users_id']) : 0;
            $result['parent_users_name'] = !empty($dealerInfo['dealer_name']) ? strval($dealerInfo['dealer_name']) : '';
        } else {
            $result['parent_users_id'] = 0;
            $result['parent_users_name'] = '平台';
        }

        // 查询是否已提交申请
        $where = [
            'users_id' => $this->users_id
        ];
        $apply = $this->dealerApply->where($where)->find();
        $result['apply_id'] = !empty($apply['apply_id']) ? intval($apply['apply_id']) : 0;
        if (!empty($apply)) {
            if (!empty($apply['review_status']) && 2 === intval($apply['review_status'])) {
                $result = [
                    'code' => 'success',
                    'jumpPage' => '/otherpages/dealer/index'
                ];
                $this->unifyParamSuccess('申请通过', null, $result);
            } else if (!empty($apply['review_status']) && 3 === intval($apply['review_status'])) {
                $apply['review_reason'] = '申请被拒接，原因：' . $apply['review_reason'];
                $result = array_merge($apply, $result);
            } else if (!empty($apply['review_status']) && 1 === intval($apply['review_status'])) {
                $apply['review_reason'] = '正在审核中，请耐心等待..';
                $result = array_merge($apply, $result);
            }
            $result['mobile'] = !empty($apply['dealer_mobile']) ? intval($apply['dealer_mobile']) : 0;
            $result['dealer_mobile'] = !empty($apply['dealer_mobile']) ? intval($apply['dealer_mobile']) : 0;
        }

        // 返回数据
        if (!empty($isReturn)) {
            return $result;
        } else {
            $this->unifyParamSuccess('查询成功', null, $result);
        }
    }

    // 添加分销商申请
    public function addDealerApply()
    {
        // 分销商名称及分销商手机号码
        if (empty($this->param['dealer_name']) || empty($this->param['dealer_mobile'])) $this->error('请填写申请信息');

        // 如果再次提交则删除上一次提交的申请
        $where = [
            'users_id' => $this->users_id
        ];
        $this->dealerApply->where($where)->delete(true);

        // 申请分销商数据
        $insert = [
            'users_id' => $this->users_id,
            'dealer_name' => !empty($this->param['dealer_name']) ? strval($this->param['dealer_name']) : '',
            'dealer_mobile' => !empty($this->param['dealer_mobile']) ? strval($this->param['dealer_mobile']) : '',
            'apply_type' => 0,
            'apply_time' => $this->times,
            'review_status' => 1,
            'review_time' => 0,
            'review_reason' => '',
            'add_time' => $this->times,
            'update_time' => $this->times,
        ];
        $applyID = $this->dealerApply->insertGetId($insert);
        if (!empty($applyID)) {
            // 获取分销商信息
            $dealerApply = $this->getDealerApply(true);
            if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
                $this->success('提交成功', null, $dealerApply);
            } else {
                // 返回数据
                $this->unifyParamSuccess('提交成功', null, $dealerApply);
            }
        } else {
            $this->error('提交失败');
        }
    }

    // 获取分销商信息
    public function getDealerData()
    {
        // 分销商信息
        $dealer = !empty($this->users['dealer']) ? $this->users['dealer'] : [];
        if (empty($dealer)) {
            $where = [
                'users_id' => $this->users_id
            ];
            $dealer = $this->dealer->where($where)->find();
        }
        $dealer['dealer_money'] = unifyPriceHandle($dealer['dealer_money']);
        $dealer['freeze_money'] = unifyPriceHandle($dealer['freeze_money']);
        $dealer['withdraw_money'] = unifyPriceHandle($dealer['withdraw_money']);

        // 分销订单佣金计算处理，此处仅获取未结算分销订单
        $dealerOrder = $this->dealerOrderRebateHandle();
        $notYetReachMoney = 0;
        foreach ($dealerOrder as $key => $value) {
            if (intval($dealer['users_id']) === intval($value['dealer_users_id']) && intval($dealer['dealer_id']) === intval($value['dealer_id'])) {
                $notYetReachMoney = floatval($notYetReachMoney) + floatval($value['order_one_rebate']);
            }
            else if (intval($dealer['users_id']) !== intval($value['dealer_users_id']) && intval($dealer['dealer_id']) !== intval($value['dealer_id'])) {
                $notYetReachMoney = floatval($notYetReachMoney) + floatval($value['order_two_rebate']);
            }
        }
        $dealer['not_yet_reach'] = !empty($notYetReachMoney) ? unifyPriceHandle($notYetReachMoney) : 0;

        // 查询分销商上级信息
        $dealer['parentDealer'] = [];
        if (!empty($this->users['parent_users_id']) && !empty($this->users['parent_dealer_id'])) {
            $where = [
                'users_id' => $this->users['parent_users_id'],
                'dealer_id' => $this->users['parent_dealer_id']
            ];
            $parentDealer = $this->dealer->where($where)->find();
            $dealer['parentDealer'] = !empty($parentDealer) ? $parentDealer : [];
        }

        $result = [
            'users' => $this->users,
            'dealer' => !empty($dealer) ? $dealer : [],
        ];
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取分销商订单
    public function getDealerOrderList()
    {
        // 分销订单佣金计算处理
        $result = $this->dealerOrderRebateHandle($this->param);

        // 订单ID数组，查询订单商品详情
        $order_ids = get_arr_column($result['data'], 'order_id');
        $where = [
            'order_id' => ['IN', $order_ids]
        ];
        $details = Db::name('shop_order_details')->where($where)->select();
        $details = !empty($details) ? group_same_key($details, 'order_id') : [];

        // 数据处理
        foreach ($result['data'] as $key => $value) {
            // 下单时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 用户头像
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            // 分销订单结算状态
            $value['handle_rebate_name'] = !empty($value['handle_rebate']) ? '已结算' : '未结算';
            // 会员昵称/用户名
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            // $oneLevelRebate = !empty($value['one_level_rebate']) ? intval($value['one_level_rebate']) / 100 : 0;
            // $twoLevelRebate = !empty($value['two_level_rebate']) ? intval($value['two_level_rebate']) / 100 : 0;

            // 订单详情数据
            $details_1 = !empty($details[$value['order_id']]) ? $details[$value['order_id']] : [];
            foreach ($details_1 as $key_1 => $value_1) {
                // 图片处理
                $value_1['litpic'] = get_default_pic($value_1['litpic'], true);
                // 规格处理
                $specData = !empty($value_1['data']) ? unserialize($value_1['data']) : [];
                $value_1['product_spec'] = !empty($specData['product_spec']) ? $specData['product_spec'] : '';
                // 商品单佣金计算
                // $productTotalPrice = floatval($value_1['product_price']) * floatval($value_1['num']);
                // if (!empty($oneLevelRebate) && !empty($productTotalPrice)) {
                //     $value_1['product_one_rebate'] = unifyPriceHandle(floatval($oneLevelRebate) * floatval($productTotalPrice));
                // }
                // if (!empty($twoLevelRebate) && !empty($productTotalPrice)) {
                //     $value_1['product_two_rebate'] = unifyPriceHandle(floatval($twoLevelRebate) * floatval($productTotalPrice));
                // }

                $details_1[$key_1] = $value_1;
            }
            // 重载订单详情
            $value['details'] = !empty($details_1) ? $details_1 : [];

            // 重载订单数据
            $result['data'][$key] = $value;
        }

        $result['tabList'] = [
            ['value' => -1, 'text' => '全部'],
            ['value' => 0, 'text' => '未结算'],
            ['value' => 1, 'text' => '已结算'],
        ];

        $result['users'] = !empty($this->users) ? $this->users : [];
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取分销商客户
    public function getDealerCustomerList()
    {
        $where = [
            'is_dealer' => 0,
            'parent_users_id' => $this->users_id,
        ];
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $result = Db::name('users')->where($where)->order('users_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($result) && $result = $result->toArray();

        // 查询客户的订单数
        $users_ids = get_arr_column($result['data'], 'users_id');
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['IN', $users_ids]
        ];
        $field = 'users_id, count(order_id) as order_num';
        $orderNum = Db::name('shop_order')->field($field)->group('users_id')->where($where)->getAllWithIndex('users_id');
        // dump($orderNum);exit;

        // 查询客户最后一次购买时间
        $where = [
            'dealer_order' => 1,
            'users_id' => ['IN', $users_ids],
            'order_status' => ['IN', [0, 1, 2, 3]],
        ];
        $field = 'order_id, users_id, max(add_time) as add_time';
        $lastOrderTime = Db::name('shop_order')->field($field)->where($where)->group('order_id')->getAllWithIndex('users_id');
        
        // 查询这个用户给上级分销商获利多少总佣金
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['IN', $users_ids]
        ];
        $field = 'order_id, users_id';
        $shopOrder = Db::name('shop_order')->field($field)->where($where)->select();
        $order_ids = !empty($shopOrder) ? get_arr_column($shopOrder, 'order_id') : [];
        // 查询佣金记录
        $where = [
            'log_type' => 1,
            'order_id' => ['IN', $order_ids],
            // 'users_id' => $referrer_users_id,
            // 'dealer_id' => $referrer_dealer_id,
        ];
        $field = 'order_id, log_action_money';
        $dealerMoneyLog = $this->dealerMoneyLog->field($field)->where($where)->getAllWithIndex('order_id');
        foreach ($shopOrder as $key => $value) {
            $logActionMoney = 0;
            if (!empty($dealerMoneyLog[$value['order_id']]['log_action_money'])) {
                $logActionMoney = floatval($dealerMoneyLog[$value['order_id']]['log_action_money']);
            }
            $shopOrder[$key]['dealer_total_money'] = !empty($logActionMoney) ? floatval($logActionMoney) : 0;
        }
        $shopOrder = !empty($shopOrder) ? group_same_key($shopOrder, 'users_id') : [];

        // 数据处理
        foreach ($result['data'] as $key => $value) {
            $value['reg_time'] = date('Y-m-d H:i:s', $value['reg_time']);
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['order_num'] = !empty($orderNum[$value['users_id']]['order_num']) ? intval($orderNum[$value['users_id']]['order_num']) : 0;
            $value['bind_dealer_time'] = !empty($value['bind_dealer_time']) ? date('Y-m-d H:i:s', $value['bind_dealer_time']) : '';
            $value['last_order_time'] = !empty($lastOrderTime[$value['users_id']]['add_time']) ? intval($lastOrderTime[$value['users_id']]['add_time']) : 0;
            $value['last_order_time'] = !empty($value['last_order_time']) ? date('Y-m-d H:i:s', $value['last_order_time']) : '尚未下单';
            $value['dealer_total_money'] = !empty($shopOrder[$value['users_id']]) ? unifyPriceHandle(array_sum(get_arr_column($shopOrder[$value['users_id']], 'dealer_total_money'))) : 0;
            $result['data'][$key] = $value;
        }

        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取分销商下级
    public function getDealerSubordinateList()
    {
        $where = [
            'b.is_dealer' => 1,
            'b.parent_users_id' => $this->users_id,
        ];
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.head_pic, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $result = $this->dealer->alias('a')->field($field)->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->order('a.dealer_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($result) && $result = $result->toArray();
        // dump($result);exit;
        // 查询分销商的客户数
        $users_ids = get_arr_column($result['data'], 'users_id');
        $dealer_ids = get_arr_column($result['data'], 'dealer_id');
        $where = [
            'is_del' => 0,
            'is_lock' => 0,
            'is_dealer' => 0,
            'parent_users_id' => ['IN', $users_ids],
            'parent_dealer_id' => ['IN', $dealer_ids]
        ];
        $field = 'parent_users_id, count(users_id) as users_num';
        $usersNum = Db::name('users')->field($field)->group('parent_users_id')->where($where)->getAllWithIndex('parent_users_id');
        // dump($usersNum);exit;

        // 查询这个下级分销商给上级分销商获利多少总佣金
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['IN', $users_ids]
        ];
        $field = 'order_id, users_id';
        $dealerOrder = Db::name('shop_order')->field($field)->where($where)->select();
        $order_ids = !empty($dealerOrder) ? get_arr_column($dealerOrder, 'order_id') : [];
        // 查询佣金记录
        $where = [
            'log_type' => 1,
            'order_id' => ['IN', $order_ids],
            // 'users_id' => $referrer_users_id,
            // 'dealer_id' => $referrer_dealer_id,
        ];
        $field = 'order_id, log_action_money';
        $dealerMoneyLog = $this->dealerMoneyLog->field($field)->where($where)->getAllWithIndex('order_id');
        foreach ($dealerOrder as $key => $value) {
            $logActionMoney = 0;
            if (!empty($dealerMoneyLog[$value['order_id']]['log_action_money'])) {
                $logActionMoney = floatval($dealerMoneyLog[$value['order_id']]['log_action_money']);
            }
            $dealerOrder[$key]['dealer_total_money'] = !empty($logActionMoney) ? floatval($logActionMoney) : 0;
        }
        $dealerOrder = !empty($dealerOrder) ? group_same_key($dealerOrder, 'users_id') : [];

        // 查询这个下级分销商给上级分销商获利多少总佣金
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['NOT IN', $users_ids],
            'dealer_users_id' => ['IN', $users_ids]
        ];
        
        $field = 'order_id, users_id, dealer_users_id';
        $usersOrder = Db::name('shop_order')->field($field)->where($where)->select();
        $order_ids = !empty($usersOrder) ? get_arr_column($usersOrder, 'order_id') : [];
        // 查询佣金记录
        $where = [
            'log_type' => 1,
            'order_id' => ['IN', $order_ids],
            // 'users_id' => $referrer_users_id,
            // 'dealer_id' => $referrer_dealer_id,
        ];
        $field = 'order_id, log_action_money';
        $dealerMoneyLog = $this->dealerMoneyLog->field($field)->where($where)->getAllWithIndex('order_id');
        foreach ($usersOrder as $key => $value) {
            $logActionMoney = 0;
            if (!empty($dealerMoneyLog[$value['order_id']]['log_action_money'])) {
                $logActionMoney = floatval($dealerMoneyLog[$value['order_id']]['log_action_money']);
            }
            $usersOrder[$key]['users_total_money'] = !empty($logActionMoney) ? floatval($logActionMoney) : 0;
        }
        $usersOrder = !empty($usersOrder) ? group_same_key($usersOrder, 'dealer_users_id') : [];

        // 数据处理
        foreach ($result['data'] as $key => $value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['users_num'] = !empty($usersNum[$value['users_id']]['users_num']) ? intval($usersNum[$value['users_id']]['users_num']) : 0;
            $value['dealer_total_money'] = !empty($dealerOrder[$value['users_id']]) ? unifyPriceHandle(array_sum(get_arr_column($dealerOrder[$value['users_id']], 'dealer_total_money'))) : 0;
            $value['users_total_money'] = !empty($usersOrder[$value['users_id']]) ? unifyPriceHandle(array_sum(get_arr_column($usersOrder[$value['users_id']], 'users_total_money'))) : 0;

            $result['data'][$key] = $value;
        }
        // dump($result['data']);exit;
        
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 添加分销商提现申请信息
    public function addDealerWithdrawData()
    {
        $dealer = !empty($this->users['dealer']) ? $this->users['dealer'] : [];
        if (empty($dealer)) {
            $where = [
                'users_id' => $this->users_id
            ];
            $dealer = $this->dealer->where($where)->find();
        }
        if (empty($dealer['dealer_money'])) $this->error('您没有可提现佣金');
        if (empty($this->param['withdraw_money'])) $this->error('请正确填写提现佣金');
        if (floatval($this->param['withdraw_money']) < floatval($this->dealerConfig['dealer_least_withdrawal'])) {
            $this->error('最低提现佣金￥' . floatval($this->dealerConfig['dealer_least_withdrawal']));
        }
        if (floatval($this->param['withdraw_money']) > floatval($dealer['dealer_money'])) {
            $this->error('您最多可提现佣金￥' . floatval($dealer['dealer_money']));
        }
        $withdrawOrder = date('Ymd') . $this->times . rand(10, 100);
        $insert = [
            'users_id' => intval($dealer['users_id']),
            'dealer_id' => intval($dealer['dealer_id']),
            'withdraw_money' => floatval($this->param['withdraw_money']),
            'withdraw_type' => 1,
            'withdraw_order' => $withdrawOrder,
            'add_time' => $this->times,
            'update_time' => $this->times,
        ];
        $withdrawID = $this->dealerWithdraw->insertGetId($insert);
        if (!empty($withdrawID)) {
            // 减少分销商可提现余额，增加分销商提现中余额
            $where = [
                'users_id' => intval($dealer['users_id']),
                'dealer_id' => intval($dealer['dealer_id']),
            ];
            $update = [
                'dealer_money' => Db::raw('dealer_money-'.(strval($this->param['withdraw_money']))),
                'freeze_money' => Db::raw('freeze_money+'.(strval($this->param['withdraw_money']))),
                'update_time' => $this->times,
            ];
            $resultID = $this->dealer->where($where)->update($update);
            if (!empty($resultID)) {
                // 增加分销商可用佣金操作记录
                $dealerCommonLogic = new \weapp\DealerPlugin\logic\DealerCommonLogic;
                $dealerCommonLogic->dealerMoneyLog(['withdraw_id' => $withdrawID], $dealer, $this->param['withdraw_money']);

                $this->success('提现申请成功', dynamic_url('plugins/DealerPlugin/dealer_index'));
            } else {
                // 分销商佣金操作失败则删除刚新增的申请记录
                $this->dealerWithdraw->delete($withdrawID);
                $this->error('提现申请失败');
            }
        } else {
            $this->error('提现申请失败');
        }
    }

    // 获取分销商提现申请列表
    public function getDealerWithdrawList()
    {
        $dealer = !empty($this->users['dealer']) ? $this->users['dealer'] : [];
        if (empty($dealer)) {
            $where = [
                'users_id' => $this->users_id
            ];
            $dealer = $this->dealer->where($where)->find();
        }
        $dealer_id = !empty($dealer['dealer_id']) ? intval($dealer['dealer_id']) : 0;
        // 年份信息
        $queryYears = !empty($this->param['queryYears']) ? intval($this->param['queryYears']) : intval(date('Y'));
        // 月份信息
        $queryMonth = !empty($this->param['queryMonth']) ? intval($this->param['queryMonth']) : intval(date('m'));
        // 年月信息
        $monthText = $queryYears . '年' . $queryMonth . '月';
        // 查询月份的月初到月末时间
        $monthValue = $queryYears . '-' . $queryMonth;
        $queryStart = strtotime($monthValue);
        $queryEnd = mktime(23, 59, 59, date('m', strtotime($monthValue))+1, 00);
        $where = [
            'dealer_id' => $dealer_id,
            'users_id' => $this->users_id,
            'add_time' => ['between', [$queryStart, $queryEnd]]
        ];
        if (!empty($this->param['reviewStatus'])) $where['review_status'] = intval($this->param['reviewStatus']);
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $result = $this->dealerWithdraw->where($where)->order('withdraw_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($result) && $result = $result->toArray();

        // 数据处理
        foreach ($result['data'] as $key => $value) {
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);

            $result['data'][$key] = $value;
        }

        $result['tabList'] = [
            ['value' => 0, 'text' => '全部'],
            ['value' => 1, 'text' => '审核中'],
            ['value' => 2, 'text' => '待打款'],
            ['value' => 3, 'text' => '拒绝'],
            ['value' => 4, 'text' => '已打款'],
        ];

        $result['monthText'] = !empty($monthText) ? $monthText : '';
        $result['monthValue'] = !empty($monthValue) ? $monthValue : '';
        $result['queryMonth'] = !empty($queryMonth) ? $queryMonth : 0;
        $result['queryYears'] = !empty($queryYears) ? $queryYears : 0;
        // dump($result);exit;
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取分销商佣金明细
    public function getDealerMoneyList()
    {
        $dealer = !empty($this->users['dealer']) ? $this->users['dealer'] : [];
        if (empty($dealer)) {
            $where = [
                'users_id' => $this->users_id
            ];
            $dealer = $this->dealer->where($where)->find();
        }
        $dealer_id = !empty($dealer['dealer_id']) ? intval($dealer['dealer_id']) : 0;
        // 年份信息
        $queryYears = !empty($this->param['queryYears']) ? intval($this->param['queryYears']) : intval(date('Y'));
        // 月份信息
        $queryMonth = !empty($this->param['queryMonth']) ? intval($this->param['queryMonth']) : intval(date('m'));
        // 年月信息
        $monthText = $queryYears . '年' . $queryMonth . '月';
        // 查询月份的月初到月末时间
        $monthValue = $queryYears . '-' . $queryMonth;
        $queryStart = strtotime($monthValue);
        $queryEnd = mktime(23, 59, 59, date('m', strtotime($monthValue))+1, 00);
        $where = [
            'a.dealer_id' => $dealer_id,
            'a.users_id' => $this->users_id,
            'a.add_time' => ['between', [$queryStart, $queryEnd]]
        ];
        // 如果是移动H5端则去掉时间条件
        if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) unset($where['a.add_time']);
        $field = 'a.*, b.review_status';
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $result = $this->dealerMoneyLog->alias('a')->field($field)->where($where)->join('__WEAPP_DEALER_WITHDRAW__ b', 'a.withdraw_id = b.withdraw_id', 'LEFT')->order('a.log_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($result) && $result = $result->toArray();

        // 数据处理
        foreach ($result['data'] as $key => $value) {
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            if (1 === intval($value['log_type'])) {
                $value['log_note'] = '分销订单结算佣金';
            } else if (2 === intval($value['log_type'])) {
                $reviewStatus = '待审核';
                if (2 === intval($value['review_status'])) {
                    $reviewStatus = '已同意';
                } else if (3 === intval($value['review_status'])) {
                    $reviewStatus = '已拒绝';
                } else if (4 === intval($value['review_status'])) {
                    $reviewStatus = '已入账';
                }
                $value['log_note'] = '提现佣金到余额 [' . $reviewStatus . ']';
            } else if (3 === intval($value['log_type'])) {
                $value['log_note'] = '提现被拒绝，返还佣金';
            }
            $value['log_after_money'] = unifyPriceHandle($value['log_after_money']);
            $value['log_action_money'] = unifyPriceHandle($value['log_action_money']);
            $result['data'][$key] = $value;
        }

        $result['monthText'] = !empty($monthText) ? $monthText : '';
        $result['monthValue'] = !empty($monthValue) ? $monthValue : '';
        $result['queryMonth'] = !empty($queryMonth) ? $queryMonth : 0;
        $result['queryYears'] = !empty($queryYears) ? $queryYears : 0;
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 分销商绑定客户处理
    public function dealerBindUsersHandle()
    {
        $update = [
            'update_time' => $this->times,
        ];
        $usersData = Db::name('users')->where(['users_id' => $this->users_id])->find();
        if (empty($usersData['parent_users_id']) && empty($usersData['parent_dealer_id'])) {
            // 如果有推荐注册的分销商ID信息则查询并绑定
            $parentUsersID = !empty($this->param['parent_users_id']) ? intval($this->param['parent_users_id']) : 0;
            $parentDealerID = !empty($this->param['parent_dealer_id']) ? intval($this->param['parent_dealer_id']) : 0;
            $parentDealer = [];
            if (!empty($parentUsersID) && !empty($parentDealerID)) {
                $where = [
                    'a.dealer_status' => 1,
                    'a.users_id' => $parentUsersID,
                    'a.dealer_id' => $parentDealerID,
                ];
                $field = 'a.*, b.is_dealer, b.parent_users_id, b.parent_dealer_id';
                $parentDealer = Db::name('weapp_dealer')->alias('a')->field($field)->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->find();
                $parentDealer = !empty($parentDealer) ? $parentDealer : [];
                $dealerOpen = getUsersConfigData('dealer.dealer_open');
                if ((isset($dealerOpen) && 0 === intval($dealerOpen)) || (!empty($parentDealer['users_id']) && intval($usersData['users_id']) === intval($parentDealer['users_id']))) {
                    $parentDealer = [];
                }
            }
            if (!empty($parentDealer) && empty($usersData['is_dealer'])) {
                // 如果当前登录用户没有上级分销商则绑定分销商
                if (empty($usersData['parent_users_id']) && empty($usersData['parent_dealer_id'])) {
                    $update['parent_users_id'] = intval($parentDealer['users_id']);
                    $update['parent_dealer_id'] = intval($parentDealer['dealer_id']);
                    $update['bind_dealer_time'] = $this->times;
                }
                // 如果当前用户绑定的上级分销商有上级分销商，有则绑定为顶级分销商
                if (!empty($parentDealer['parent_users_id']) && !empty($parentDealer['parent_dealer_id'])) {
                    $update['top_users_id'] = intval($parentDealer['parent_users_id']);
                    $update['top_dealer_id'] = intval($parentDealer['parent_dealer_id']);
                    if (empty($update['bind_dealer_time'])) $update['bind_dealer_time'] = $this->times;
                }
            }
            // 绑定分销商客户
            $resultID = Db::name('users')->where(['users_id' => $this->users_id])->update($update);
            if (!empty($resultID)) {
                if (!model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) $this->success('绑定成功');
            } else {
                if (!model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) $this->success('绑定失败');
            }
        } else {
            if (!model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) $this->success('已绑定过');
        }
    }

    // 分销订单佣金计算处理
    private function dealerOrderRebateHandle($param = [])
    {
        // 查询指定分销商 and 关联下级分销商 and 关联客户 的订单
        $dealer_id = isset($this->users['dealer']['dealer_id']) ? intval($this->users['dealer']['dealer_id']) : 0;
        $dealer_users_ids = [];
        if (!empty($dealer_id)) {
            $dealer_users_id = $this->dealer->where(['dealer_id'=>$dealer_id])->getField('users_id');
            if (!empty($dealer_users_id)) {
                $dealer_users_ids = Db::name('users')->where(['users_id|parent_users_id|top_users_id'=>$dealer_users_id])->column('users_id');
            }
            if (!empty($dealer_users_ids)) $where['a.dealer_users_id'] = ['IN', $dealer_users_ids];
        }

        $where = [
            'a.dealer_order' => 1,
            'a.dealer_users_id' => ['IN', $dealer_users_ids],
        ];
        $dealerOrder = [];
        // 订单列表查询
        if (!empty($param)) {
            $field = 'a.*, b.username, b.nickname, b.head_pic, b.users_money, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
            if (isset($param['handleRebate']) && in_array($param['handleRebate'], [0, 1])) $where['a.handle_rebate'] = intval($param['handleRebate']);
            $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
            $result = Db::name('shop_order')->alias('a')->field($field)->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->order('a.order_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
            !empty($result) && $result = $result->toArray();
            $dealerOrder = !empty($result['data']) ? $result['data'] : [];
        }
        // 分销商首页查询
        else {
            $where['a.handle_rebate'] = 0;
            $where['a.order_status'] = ['IN', [0, 1, 2, 3]];
            $dealerOrder = Db::name('shop_order')->alias('a')->where($where)->select();
        }

        // 数据处理
        foreach ($dealerOrder as $key => $value) {
            // 佣金计算额
            $dealerTotalAmount = 0;
            // 佣金计算方式 (订单商品合计总额 or 订单实际支付总额)
            $dealerRebate = !empty($value['dealer_rebate']) ? intval($value['dealer_rebate']) : 0;
            // 一级佣金比例
            $oneLevelRebate = !empty($value['one_level_rebate']) ? intval($value['one_level_rebate']) / 100 : 0;
            // 二级佣金比例
            $twoLevelRebate = !empty($value['two_level_rebate']) ? intval($value['two_level_rebate']) / 100 : 0;
            // 使用 订单商品合计总额 进行计算分佣
            if (!empty($dealerRebate) && 1 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_total_amount']);
            }
            // 使用 订单实际支付总额((余额抵扣+实付款)-运费) 进行计算分佣
            else if (!empty($dealerRebate) && 2 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_amount']);
                // 存在运费则扣除运费，运费不在分销佣金计算中
                $dealerTotalAmount = !empty($value['shipping_fee']) ? floatval($dealerTotalAmount) - floatval($value['shipping_fee']) : $dealerTotalAmount;
            }
            $value['dealer_total_amount'] = !empty($dealerTotalAmount) ? unifyPriceHandle($dealerTotalAmount) : 0;
            // 一级分销佣金
            if (!empty($oneLevelRebate) && !empty($dealerTotalAmount)) {
                // 计算一级返佣比例
                $value['order_one_rebate'] = unifyPriceHandle(floatval($oneLevelRebate) * floatval($dealerTotalAmount));
            }
            // 二级分销佣金
            if (!empty($twoLevelRebate) && !empty($dealerTotalAmount)) {
                // 计算一级返佣比例
                $value['order_two_rebate'] = unifyPriceHandle(floatval($twoLevelRebate) * floatval($dealerTotalAmount));
            }
            // 重载原数据
            $dealerOrder[$key] = $value;
        }

        if (!empty($param)) {
            $result['data'] = $dealerOrder;
            return $result;
        } else {
            return $dealerOrder;
        }
    }

    // 查询分销商数据
    private function getDealerInfo($paramUsersID = 0)
    {
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $where = [
            'a.users_id' => !empty($paramUsersID) ? intval($paramUsersID) : intval($this->users_id)
        ];
        return $this->dealer->alias('a')->field($field)->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->find();
    }

    // 统一携带默认参数返回
    private function unifyParamSuccess($msg = '操作成功', $url = null, $result = [])
    {
        // 分销设置
        $result['dealerConfig'] = $this->dealerConfig;
        // 获取商城店铺设置信息(后台-设置-店铺信息)
        $result['shopConf'] = model('ShopPublicHandle')->getWebShopConfig();
        // 获取指定返回的全局配置
        // model('v1.Api')->getGlobalConfig([], $result);
        if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
            $dealerController = new \app\plugins\controller\DealerPlugin;
            $paramA = !empty($this->param['a']) ? $this->param['a'] : 'errorMsg';
            $dealerController->$paramA($result);
        } else {
            // 返回结果
            $this->success($msg, $url, $result);
        }
    }
}